<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>摄影点地图</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
    }
    #map {
      width: 100%;
      height: 100vh;
    }
    .loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 24px;
      color: #333;
      z-index: 2000;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <div class="loading" id="loading">加载中...</div>

  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <script>
    const map = L.map('map').setView([0, 0], 2);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    const markers = [];
    const loadingElement = document.getElementById('loading');

    async function fetchPhotographyPoints(speciesName) {
      try {
        const response = await fetch(`http://localhost:4000/test1`);
        if (!response.ok) {
          throw new Error('网络响应不正常');
        }
        const data = await response.json();
        return data.data;
      } catch (error) {
        console.error('获取摄影点数据失败:', error);
        throw error;
      }
    }

    function clearMap() {
      markers.forEach(marker => map.removeLayer(marker));
      markers.length = 0;
    }

    async function displayPhotographyPoints(speciesName) {
      loadingElement.style.display = 'block';

      try {
        const photographyPoints = await fetchPhotographyPoints(speciesName);
        
        if (photographyPoints.length === 0) {
          loadingElement.innerHTML = '没有找到摄影点数据';
          loadingElement.style.color = 'red';
          return;
        }

        clearMap();

        photographyPoints.forEach(point => {
  const coordinates = [point.location.coordinates[1], point.location.coordinates[0]];

  // 检查后端是否返回了有效的 photo 数据
  let imgSrc = '';
  if (point.photo && point.photo.data && Array.isArray(point.photo.data)) {
    // 将二进制数组（Uint8Array）转换为 Base64 字符串
    const byteArray = new Uint8Array(point.photo.data);
    const base64String = arrayBufferToBase64(byteArray);
    imgSrc = `data:image/jpeg;base64,${base64String}`;
  } else {
    imgSrc = 'https://via.placeholder.com/300x200?text=No+Image';  // 如果没有图片数据，使用占位符
  }

  const marker = L.marker(coordinates).addTo(map);
  markers.push(marker);

  const popupContent = `
    <strong>${point.speciesName}</strong><br>
    <img src="${imgSrc}" 
         onerror="this.src='https://via.placeholder.com/300x200?text=No+Image'; this.style.display='block'" 
         style="max-width:300px; max-height:200px;"><br>
    创建时间: ${new Date(point.createdAt).toLocaleString()}
  `;

  marker.bindPopup(popupContent);
});

// 辅助函数：将二进制数据数组转换为 Base64 字符串
function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const length = bytes.byteLength;
  for (let i = 0; i < length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary); // 使用 btoa 函数将二进制数据转换为 Base64
}


        if (photographyPoints.length === 1) {
          const coordinates = [
            photographyPoints[0].location.coordinates[1],
            photographyPoints[0].location.coordinates[0]
          ];
          map.setView(coordinates, 13);
        } else if (photographyPoints.length > 1) {
          const bounds = new L.LatLngBounds(
            markers.map(marker => marker.getLatLng())
          );
          map.fitBounds(bounds);
        }
      } catch (error) {
        loadingElement.innerHTML = '加载失败: ' + error.message;
        loadingElement.style.color = 'red';
      } finally {
        loadingElement.style.display = 'none';
      }
    }

    window.addEventListener('load', () => {
      displayPhotographyPoints('Panthera tigris');
    });
  </script>
</body>
</html>
